<?php

namespace app\command;

use app\common\model\GuessOrderModel;
use app\common\model\GuessReportModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;

class GuessTop extends Command
{
    protected function configure()
    {
        $this->setName('guess_top')->setDescription('竞猜周榜统计')
            ->addOption('weeks', 'w', Option::VALUE_OPTIONAL, '可选 周数 例如 2022-42');
    }

    protected function execute(Input $input, Output $output)
    {
        if ($input->hasOption('weeks')) {
            $this->common(trim($input->getOption('weeks')));
        } else {
            $w = date('W');
            if ($w == '01') {
                $Y = date('Y') - 1;
                $weeks = $Y . '-' . date('W', strtotime($Y . "-12-31"));
            } else {
                $weeks = date('Y-') . str_pad(strval($w - 1), 2, '0',STR_PAD_LEFT );
            }
            $this->common($weeks);
        }
    }

    protected function common($weeks)
    {
        $explode = explode('-', $weeks);
        if (count($explode) !== 2) {
            return false;
        }

        $dates = getWeekDate($explode[0], $explode[1]);

        $where = " update_time BETWEEN '{$dates[0]}' and '{$dates[1]}'  and status in(2,3) ";

        $sql = "SELECT count(uid) as count,sum(amount) as amount FROM (SELECT uid,sum(amount) as amount FROM db_guess_order where {$where} GROUP BY `uid`) a limit 1";
        $list = Db::query($sql);

        $sql = "SELECT sum(profit - amount) as profit  FROM (SELECT sum(profit) as profit,sum(amount) as amount FROM db_guess_order where update_time BETWEEN '{$dates[0]}' and '{$dates[1]}'  and status=3  GROUP BY `uid`) a limit 1";

        $list1 = Db::query($sql);

        $list2 = Db::query("SELECT count(id) as count FROM db_guess_order where {$where} limit 1");

        if (!$model = GuessReportModel::where('weeks', $weeks)->find()) {
            $model = new GuessReportModel();
            $model->weeks = $weeks;
        }

        $model->years = $explode[0];
        $model->month = date('m', strtotime($dates[0]));
        $model->total_people = $list[0]['count'];
        $model->total_degree = $list2[0]['count'];
        $model->total_sales = $list[0]['amount'];
        $model->total_reward = $list1[0]['profit'];

        $model->average_reward = $model->total_reward == 0 ? $model->total_reward : bcdiv($model->total_reward, $model->total_people, 0);
        $model->status = 1;

        $model->save();
    }
}